/*
 * @Author: yangrongxin
 * @Date: 2021-08-03 17:56:14
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:26:33
 */
import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { View, Image, ScrollView } from '@tarojs/components';
import styles from './index.module.less';

// eslint-disable-next-line import/no-commonjs
const loadingImg = require('@/assets/images/loading.png');

interface IScrollContentProps {
  request: any; // 获取数据的请求方式
  ScrollItem: any; // 展示的内部滚动元素
  params: any; // 当前接口的请求参数 此参数 在组件onload的时候 进行获取
  onChange?: any; // 注入到滑动组件中的事件
  extendScrollContent?: string; // 注入对样式的扩展
  extendScrollContentWapper?: string; // 注入外层元素的样式s
  itemProps?: any; // 用于扩展子集元素的属性
  onLoadWhenShow?: boolean; // 用于判断当前是不是在展示组件的时候才获取数据
  onDataFetch?: any; // 用户监听当前获取数据的数据变更 返回当前请求数据的响应体
  enabledRefresh?: boolean; // 当前是不是开启下拉刷新
  enabledLoadingIcon?: boolean; // 是不是展示加载过程中的加载图标
}

const ScrollContent = (props: IScrollContentProps, ref: any) => {
  const {
    request,
    ScrollItem = <View>展示内容</View>,
    params,
    extendScrollContent,
    extendScrollContentWapper,
    itemProps,
    onChange,
    onLoadWhenShow,
    enabledRefresh = true, // 默认当前的滚动加载
    enabledLoadingIcon = true,
    onDataFetch,
  } = props;

  console.log('onLoadWhenShow', onLoadWhenShow);

  const [dataList, setDataList] = useState<any[]>([]);
  const [pageNum, setPageNum] = useState<number>(1);
  const [canLoadingMore, setCanLoadingMore] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false); // 控制当前是否展示加载更多的展示
  const [refresherTrigger, setRefresherTrigger] = useState(false);
  const pageSize = 50;

  /*
   * otherParams 当前请求的请求参数
   * isReload 当前是不是重新加载获取请求数据
   */
  const getData = (otherParams, isReload = false) => {
    setLoading(true);
    if (isReload) setPageNum(1);
    request({
      pageNum: isReload ? 1 : pageNum,
      ...otherParams,
      pageSize,
    }).then((res: any = {}) => {
      const { content = [], total: resTotal } = res;
      let newContentList = content;
      if (canLoadingMore && !isReload) {
        newContentList = dataList.concat(content);
      }
      setDataList(newContentList);
      setCanLoadingMore(resTotal > newContentList.length);
      setTimeout(() => {
        setRefresherTrigger(false);
        setLoading(false);
      }, 500);
      onDataFetch && onDataFetch(res);
      console.log('getScrollContentData', res);
    });
  };

  useEffect(() => {
    if (params && onLoadWhenShow) getData(params);
  }, ['']);

  useImperativeHandle(ref, () => ({
    // 用于其他组件刷新参数的方法
    reload: (data: any, isReload: boolean = false) => getData(data, isReload),
  }));

  console.log('canLoadingMore', canLoadingMore);

  return (
    // 展示滚动的区域
    <ScrollView
      scrollY
      scrollAnchoring
      scrollWithAnimation
      className={`${styles.scrollWapper} ${extendScrollContentWapper}`}
      onScrollToLower={() => {
        if (canLoadingMore && !loading) {
          let newPageNum: number = pageNum;
          newPageNum += 1;
          setPageNum(newPageNum);
          getData({
            ...params,
            pageNum: newPageNum,
          });
        }
      }}
      refresherEnabled={enabledRefresh}
      onRefresherRefresh={() => {
        setRefresherTrigger(true);
        getData(params, true);
      }}
      refresherTriggered={refresherTrigger}
    >
      <View className={`${styles.scrollContent} ${extendScrollContent}`}>
        {enabledLoadingIcon && loading && <Image className={styles.loadingWapper} src={loadingImg} mode="aspectFill" />}
        {(!enabledLoadingIcon || !loading) &&
          dataList.map((item: any) => {
            return <ScrollItem key={String(Math.random())} onChange={onChange} {...item} {...itemProps} />;
          })}
        {/* 展示当前为空的图片 */}
        {!loading && dataList.length === 0 && (
          <Image
            className={styles.emptyImage}
            src="https://hxgywx.oss-cn-shenzhen.aliyuncs.com/nursing-customer/assets/empty_box.png"
            mode="aspectFill"
          />
        )}
      </View>
    </ScrollView>
  );
};

export default forwardRef(ScrollContent);
